<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>地图查询 - 校园助手</title>
    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Font Awesome -->
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <!-- 高德地图API -->
    <script src="https://webapi.amap.com/maps?v=1.4.15&key=4a86920ac36be915dbdab6d43b08fccb"></script>
    <!-- 自定义Tailwind配置 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#EC4899', // 主色调：粉色
                        secondary: '#F472B6', // 辅助色：浅粉色
                        accent: '#BE185D', // 强调色：深粉色
                        blue: '#3B82F6', // 蓝色：地图主题色
                        dark: '#1E293B', // 深色
                        light: '#FDF2F8'  // 浅色
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                    animation: {
                        'pulse-slow': 'pulse 3s cubic-bezier(0.4, 0, 0.6, 1) infinite',
                        'float': 'float 3s ease-in-out infinite',
                    },
                    keyframes: {
                        float: {
                            '0%, 100%': { transform: 'translateY(0)' },
                            '50%': { transform: 'translateY(-10px)' },
                        }
                    }
                },
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .gradient-blue {
                background: linear-gradient(135deg, #3B82F6 0%, #60A5FA 100%);
            }
            .gradient-primary {
                background: linear-gradient(135deg, #EC4899 0%, #F472B6 100%);
            }
            .text-shadow {
                text-shadow: 0 2px 4px rgba(0,0,0,0.1);
            }
            .transition-custom {
                transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            }
            
            /* 地图标签自定义样式 */
            .custom-map-label {
                background-color: rgba(255, 255, 255, 0.9);
                color: #333;
                padding: 4px 8px;
                border-radius: 4px;
                font-size: 14px;
                font-weight: bold;
                border: 1px solid #ddd;
                box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
                white-space: nowrap;
                text-align: center;
            }
        }
    </style>
    <script>
        // 页面加载时检查用户是否已登录
        window.addEventListener('DOMContentLoaded', function() {
            const token = localStorage.getItem('token');
            const username = localStorage.getItem('username');
            
            // 如果未登录，重定向到登录页面
            if (!token || !username) {
                window.location.href = '/login.html';
            } else {
                // 显示用户名
                document.getElementById('logged-in-username').textContent = username;
            }
            
            // 初始化地图
            initMap();
            
            // 设置城市搜索
            setupCitySearch();
        });
        
        // 退出登录功能
        function logout() {
            localStorage.removeItem('token');
            localStorage.removeItem('username');
            window.location.href = '/login.html';
        }
        
        // 返回主页
        function goToHomePage() {
            window.location.href = '/homepage.html';
        }
        
        // 初始化高德地图
        function initMap() {
            // 创建地图实例
            window.map = new AMap.Map('map-container', {
                zoom: 10,
                center: [106.55, 29.57], // 重庆的经纬度
                resizeEnable: true,
                showLabel: true, // 显示地图上的标签
                showBuildingBlock: true, // 显示建筑物
                defaultCursor: 'pointer' // 鼠标悬停为指针样式
            });
            
            // 添加标记 - 自定义图标和标题
            window.marker = new AMap.Marker({
                position: [106.55, 29.57],
                map: window.map,
                title: '重庆市',
                // 自定义标记点图标
                icon: new AMap.Icon({
                    size: new AMap.Size(40, 50), // 图标尺寸
                    image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png', // 图标地址
                    imageSize: new AMap.Size(40, 50) // 图标所用图片大小
                }),
                offset: new AMap.Pixel(-20, -50), // 偏移量
                // 添加标签
                label: {
                    content: '重庆市', // 标签内容
                    offset: new AMap.Pixel(-15, -60), // 标签偏移量
                    className: 'custom-map-label' // 自定义CSS类名
                }
            });
            
            // 添加地图点击事件
            window.map.on('click', function(e) {
                const lnglat = e.lnglat;
                AMap.plugin('AMap.Geocoder', function() {
                    const geocoder = new AMap.Geocoder({
                        radius: 1000,
                        extensions: "all"
                    });
                    
                    geocoder.getAddress(lnglat, function(status, result) {
                        if (status === 'complete' && result.info === 'OK') {
                            const address = result.regeocode.addressComponent;
                            const city = address.city || address.province;
                            const fullAddress = result.regeocode.formattedAddress;
                            updateMarkerAndInfo(lnglat, fullAddress, city);
                        }
                    });
                });
            });
            
            // 添加地图控件
            AMap.plugin(['AMap.ToolBar', 'AMap.Scale', 'AMap.HawkEye', 'AMap.MapType'], function() {
                // 添加工具栏
                window.map.addControl(new AMap.ToolBar());
                // 添加比例尺
                window.map.addControl(new AMap.Scale());
                // 添加鹰眼
                window.map.addControl(new AMap.HawkEye());
                // 添加地图类型切换
                window.map.addControl(new AMap.MapType());
            });
        }
        
        // 更新标记和信息
        function updateMarkerAndInfo(lnglat, address, city) {
            // 更新标记位置和标题
            window.marker.setPosition(lnglat);
            window.marker.setTitle(address);
            
            // 更新标记标签
            window.marker.setLabel({
                content: city, // 使用城市名称作为标签内容
                offset: new AMap.Pixel(-15, -60),
                className: 'custom-map-label'
            });
            
            // 显示地址信息
            document.getElementById('selected-address').textContent = address;
            document.getElementById('selected-city').textContent = city;
            document.getElementById('selected-lng').textContent = lnglat.getLng().toFixed(6);
            document.getElementById('selected-lat').textContent = lnglat.getLat().toFixed(6);
            
            // 显示信息面板
            document.getElementById('location-info-panel').classList.remove('hidden');
        }
        
        // 获取当前位置
        function getCurrentLocation() {
            // 首先检查是否有权限访问位置信息
            navigator.permissions.query({ name: 'geolocation' }).then(function(permissionStatus) {
                // 如果用户已经拒绝了权限，直接显示提示
                if (permissionStatus.state === 'denied') {
                    showErrorMessage('您已拒绝位置访问权限，请在浏览器设置中开启');
                    return;
                }
                
                if (navigator.geolocation) {
                    showLoading('正在获取您的位置...');
                    // 设置获取位置的选项，增加超时时间和精度要求
                    const options = {
                        enableHighAccuracy: true,
                        timeout: 10000, // 10秒超时
                        maximumAge: 60000 // 允许使用60秒内的缓存位置
                    };
                    
                    navigator.geolocation.getCurrentPosition(
                        function(position) {
                            const { longitude, latitude } = position.coords;
                            AMap.plugin('AMap.Geocoder', function() {
                                const geocoder = new AMap.Geocoder({
                                    radius: 1000,
                                    extensions: "all"
                                });
                                
                                geocoder.getAddress([longitude, latitude], function(status, result) {
                                    if (status === 'complete' && result.info === 'OK') {
                                        const fullAddress = result.regeocode.formattedAddress;
                                        const address = result.regeocode.addressComponent;
                                        const city = address.city || address.province;
                                        
                                        // 更新地图位置
                                        const lnglat = new AMap.LngLat(longitude, latitude);
                                        window.map.setCenter(lnglat);
                                        window.map.setZoom(15);
                                        
                                        updateMarkerAndInfo(lnglat, fullAddress, city);
                                        hideLoading();
                                    } else {
                                        hideLoading();
                                        showErrorMessage('地址解析失败，请重试');
                                    }
                                });
                            });
                        },
                        function(error) {
                            hideLoading();
                            // 根据不同的错误类型显示更具体的提示信息
                            switch(error.code) {
                                case error.PERMISSION_DENIED:
                                    showErrorMessage('您拒绝了位置访问请求，请在浏览器设置中开启');
                                    break;
                                case error.POSITION_UNAVAILABLE:
                                    showErrorMessage('位置信息不可用，请检查网络连接');
                                    break;
                                case error.TIMEOUT:
                                    showErrorMessage('获取位置超时，请稍后重试');
                                    break;
                                default:
                                    showErrorMessage('获取位置失败，请确保已授权位置访问');
                            }
                        },
                        options
                    );
                } else {
                    showErrorMessage('您的浏览器不支持地理定位功能');
                }
            });
        }
        
        // 城市搜索功能
        function setupCitySearch() {
            const searchInput = document.getElementById('city-search-input');
            const searchResults = document.getElementById('search-results');
            
            searchInput.addEventListener('input', function() {
                const keyword = this.value.trim();
                if (keyword.length < 2) {
                    searchResults.classList.add('hidden');
                    return;
                }
                
                AMap.plugin('AMap.Autocomplete', function() {
                    const autoOptions = {
                        city: "全国",
                        input: keyword
                    };
                    const autocomplete = new AMap.Autocomplete(autoOptions);
                    
                    autocomplete.search(keyword, function(status, result) {
                        if (status === 'complete' && result.tips && result.tips.length > 0) {
                            searchResults.innerHTML = '';
                            result.tips.slice(0, 5).forEach(tip => {
                                const item = document.createElement('div');
                                item.className = 'px-4 py-2 hover:bg-gray-100 cursor-pointer';
                                item.textContent = tip.name;
                                item.addEventListener('click', function() {
                                    searchInput.value = tip.name;
                                    searchResults.classList.add('hidden');
                                    searchLocation(tip.name);
                                });
                                searchResults.appendChild(item);
                            });
                            searchResults.classList.remove('hidden');
                        } else {
                            searchResults.classList.add('hidden');
                        }
                    });
                });
            });
            
            // 点击外部关闭搜索结果
            document.addEventListener('click', function(event) {
                if (!searchInput.contains(event.target) && !searchResults.contains(event.target)) {
                    searchResults.classList.add('hidden');
                }
            });
        }
        
        // 搜索位置
        function searchLocation(locationName) {
            showLoading('正在搜索位置...');
            
            AMap.plugin('AMap.Geocoder', function() {
                const geocoder = new AMap.Geocoder({
                    radius: 1000,
                    extensions: "all"
                });
                
                geocoder.getLocation(locationName, function(status, result) {
                    if (status === 'complete' && result.info === 'OK') {
                        const lnglat = result.geocodes[0].location;
                        const formattedAddress = result.geocodes[0].formattedAddress;
                        const addressComponent = result.geocodes[0].addressComponent;
                        const city = addressComponent.city || addressComponent.province;
                        
                        // 更新地图位置和缩放级别
                        window.map.setCenter(lnglat);
                        window.map.setZoom(12);
                        
                        // 更新标记信息
                        updateMarkerAndInfo(lnglat, formattedAddress, city);
                        
                        // 添加动画效果
                        window.marker.setAnimation('AMAP_ANIMATION_BOUNCE');
                        setTimeout(function() {
                            window.marker.setAnimation('AMAP_ANIMATION_NONE');
                        }, 2000);
                        
                        hideLoading();
                    } else {
                        hideLoading();
                        showErrorMessage('未找到该位置，请尝试其他关键词');
                    }
                });
            });
        }
        
        // 工具函数
        function showLoading(message) {
            document.getElementById('loading-message').textContent = message;
            document.getElementById('loading-modal').classList.remove('hidden');
        }
        
        function hideLoading() {
            document.getElementById('loading-modal').classList.add('hidden');
        }
        
        function showErrorMessage(message) {
            document.getElementById('error-message').textContent = message;
            document.getElementById('error-modal').classList.remove('hidden');
        }
        
        function showSuccessMessage(message) {
            document.getElementById('success-message').textContent = message;
            document.getElementById('success-modal').classList.remove('hidden');
        }
        
        // 复制位置信息
        function copyLocationInfo() {
            const address = document.getElementById('selected-address').textContent;
            const city = document.getElementById('selected-city').textContent;
            const lng = document.getElementById('selected-lng').textContent;
            const lat = document.getElementById('selected-lat').textContent;
            
            const info = `地址：${address}\n城市：${city}\n经度：${lng}\n纬度：${lat}`;
            
            navigator.clipboard.writeText(info).then(function() {
                showSuccessMessage('位置信息已复制到剪贴板');
            }).catch(function() {
                showErrorMessage('复制失败，请手动复制');
            });
        }
    </script>
</head>
<body class="bg-gradient-to-br from-blue-50 to-white min-h-screen flex flex-col">
    <!-- 导航栏 -->
    <header class="bg-white shadow-md sticky top-0 z-50">
        <div class="container mx-auto px-4 py-4 flex justify-between items-center">
            <div class="flex items-center space-x-2">
                <button class="text-gray-500 hover:text-blue-500 transition-custom md:hidden" onclick="goToHomePage()">
                    <i class="fa fa-arrow-left text-xl"></i>
                </button>
                <i class="fa fa-map-marker text-blue text-2xl"></i>
                <h1 class="text-xl font-bold text-gray-800">地图查询 - 校园助手</h1>
            </div>
            <div class="flex items-center space-x-4">
                <!-- 返回主页按钮（桌面版） -->
                <button class="hidden md:block px-4 py-2 bg-blue/10 text-blue rounded-lg hover:bg-blue/20 transition-custom" onclick="goToHomePage()">
                    <i class="fa fa-home mr-2"></i>返回主页
                </button>
                <!-- 用户信息展示 -->
                <div class="flex items-center space-x-2">
                    <span id="logged-in-username" class="text-gray-600"></span>
                    <button id="logout-button" class="text-gray-500 hover:text-red-500 transition-custom" onclick="logout()">
                        <i class="fa fa-sign-out"></i>
                    </button>
                </div>
            </div>
        </div>
    </header>

    <!-- 主要内容 -->
    <main class="flex-grow container mx-auto px-4 py-8">
        <!-- 地图和搜索功能 -->
        <section class="mb-8">
            <div class="bg-white rounded-xl shadow-lg p-6">
                <div class="flex flex-col md:flex-row justify-between items-center mb-6">
                    <h3 class="text-lg font-semibold text-gray-800">位置搜索</h3>
                    <div class="mt-4 md:mt-0 w-full md:w-auto">
                        <div class="relative">
                            <input type="text" id="city-search-input" placeholder="搜索城市或地点..." 
                                class="pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 w-full md:w-64">
                            <i class="fa fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
                        </div>
                        <div id="search-results" class="absolute z-10 mt-1 bg-white shadow-lg rounded-lg hidden w-full md:w-64"></div>
                    </div>
                </div>
                <!-- 地图容器 -->
                <div id="map-container" class="w-full h-[500px] rounded-lg border border-gray-200"></div>
                <div class="mt-4 flex flex-wrap gap-2">
                    <button class="px-3 py-1 text-sm bg-blue/10 text-blue rounded-lg hover:bg-blue/20 transition-custom" onclick="getCurrentLocation()">
                        <i class="fa fa-map-marker mr-1"></i>获取当前位置
                    </button>
                </div>
            </div>
        </section>
        
        <!-- 位置信息面板 -->
        <section id="location-info-panel" class="mb-8 hidden">
            <div class="bg-white rounded-xl shadow-lg p-6">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="text-lg font-semibold text-gray-800">
                        <i class="fa fa-info-circle text-blue mr-2"></i>位置信息
                    </h3>
                    <button class="px-3 py-1 text-sm bg-blue/10 text-blue rounded-lg hover:bg-blue/20 transition-custom" onclick="copyLocationInfo()">
                        <i class="fa fa-copy mr-1"></i>复制信息
                    </button>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div class="space-y-3">
                        <div class="flex items-start">
                            <div class="w-24 text-gray-500">地址：</div>
                            <div class="flex-grow text-gray-800" id="selected-address">--</div>
                        </div>
                        <div class="flex items-start">
                            <div class="w-24 text-gray-500">城市：</div>
                            <div class="flex-grow text-gray-800" id="selected-city">--</div>
                        </div>
                    </div>
                    <div class="space-y-3">
                        <div class="flex items-start">
                            <div class="w-24 text-gray-500">经度：</div>
                            <div class="flex-grow text-gray-800" id="selected-lng">--</div>
                        </div>
                        <div class="flex items-start">
                            <div class="w-24 text-gray-500">纬度：</div>
                            <div class="flex-grow text-gray-800" id="selected-lat">--</div>
                        </div>
                    </div>
                </div>
            </div>
        </section>
        
        <!-- 地图功能说明 -->
        <section class="mb-8">
            <div class="bg-white rounded-xl shadow-lg p-6">
                <h3 class="text-lg font-semibold text-gray-800 mb-4">
                    <i class="fa fa-lightbulb-o text-yellow-500 mr-2"></i>使用说明
                </h3>
                <div class="space-y-3 text-gray-600">
                    <div class="flex items-start">
                        <i class="fa fa-check-circle text-green-500 mt-1 mr-2"></i>
                        <p>在搜索框中输入城市或地点名称，快速定位到目标位置</p>
                    </div>
                    <div class="flex items-start">
                        <i class="fa fa-check-circle text-green-500 mt-1 mr-2"></i>
                        <p>点击地图上的任意位置，查看该地点的详细信息</p>
                    </div>
                    <div class="flex items-start">
                        <i class="fa fa-check-circle text-green-500 mt-1 mr-2"></i>
                        <p>使用"获取当前位置"按钮，定位到您的实际位置</p>
                    </div>
                    <div class="flex items-start">
                        <i class="fa fa-check-circle text-green-500 mt-1 mr-2"></i>
                        <p>复制位置信息功能可以将经纬度等信息复制到剪贴板</p>
                    </div>
                </div>
            </div>
        </section>
    </main>

    <!-- 页脚 -->
    <footer class="bg-white border-t border-gray-200 py-6">
        <div class="container mx-auto px-4 text-center text-gray-500 text-sm">
            <p>© 2024 校园助手 - 地图服务</p>
        </div>
    </footer>

    <!-- 加载中模态框 -->
    <div id="loading-modal" class="fixed inset-0 flex items-center justify-center bg-black/50 z-50 hidden">
        <div class="bg-white rounded-xl p-6 max-w-md w-full flex flex-col items-center">
            <div class="w-16 h-16 border-4 border-blue/30 border-t-blue rounded-full animate-spin mb-4"></div>
            <h3 class="text-lg font-semibold text-gray-800 mb-2">处理中</h3>
            <p class="text-gray-600 text-center" id="loading-message">正在处理您的请求，请稍候...</p>
        </div>
    </div>

    <!-- 错误提示模态框 -->
    <div id="error-modal" class="fixed inset-0 flex items-center justify-center bg-black/50 z-50 hidden">
        <div class="bg-white rounded-xl p-6 max-w-md w-full mx-4">
            <div class="flex items-center mb-4">
                <div class="w-10 h-10 rounded-full bg-red-100 flex items-center justify-center text-red-500 mr-3">
                    <i class="fa fa-exclamation-triangle text-red-600"></i>
                </div>
                <h3 class="text-lg font-semibold text-gray-800">错误</h3>
            </div>
            <p class="text-gray-600 mb-4" id="error-message">操作失败，请重试。</p>
            <div class="flex justify-end">
                <button class="px-4 py-2 bg-red-50 text-red-600 rounded-lg hover:bg-red-100 transition-custom border border-red-200" onclick="document.getElementById('error-modal').classList.add('hidden')">
                    关闭
                </button>
            </div>
        </div>
    </div>

    <!-- 成功提示模态框 -->
    <div id="success-modal" class="fixed inset-0 flex items-center justify-center bg-black/50 z-50 hidden">
        <div class="bg-white rounded-xl p-6 max-w-md w-full mx-4">
            <div class="flex items-center mb-4">
                <div class="w-10 h-10 rounded-full bg-green-100 flex items-center justify-center text-green-500 mr-3">
                    <i class="fa fa-check text-green-600"></i>
                </div>
                <h3 class="text-lg font-semibold text-gray-800">成功</h3>
            </div>
            <p class="text-gray-600 mb-4" id="success-message">操作已成功完成。</p>
            <div class="flex justify-end">
                <button class="px-4 py-2 bg-green-50 text-green-600 rounded-lg hover:bg-green-100 transition-custom border border-green-200" onclick="document.getElementById('success-modal').classList.add('hidden')">
                    关闭
                </button>
            </div>
        </div>
    </div>
</body>
</html>